from django.core.exceptions import ObjectDoesNotExist
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from aweirunner.utils import loader, response
from auto_dj_test.conf.MyLogger import MyLogger
from aweirunner.utils.decorator import request_log
from aweirunner.utils.parser import Format
from aweirunner import models

logger = MyLogger(__name__).logger

config_err = {
    "success": False,
    "msg": "指定的配置文件不存在",
    "code": "787878"
}


@api_view(['POST'])
@permission_classes([AllowAny])
def run_api(request):
    """
     run api by body
    :param request:
    :return:
    """
    name = request.data.get('config')
    api = Format(request.data)
    api.parse()
    logger.info(f"第一阶段解析完成{api.testcase}")
    config = None
    if name != "请选择" and name is not None:
        try:
            logger.info(f"配置名：{name}")
            config = eval(models.Config.objects.get(name=name, project__id=api.project).body)

        except ObjectDoesNotExist:
            logger.error(f"指定的请求环境不存在:{name}")
            return Response(config_err)

    logger.debug("第二阶段解析")
    summary = loader.debug_api(api.testcase, api.project, name=api.name, config=config,
                               user=request.user['username'])

    logger.info(f"summary:{summary}")
    return Response(summary)


@api_view(['GET'])
@permission_classes([AllowAny])
def run_api_pk(request, **kwargs):
    """run api by pk and config
    """
    # host = request.query_params["host"]
    api = models.API.objects.get(id=kwargs['pk'])
    name = request.query_params["config"]
    config = None if name == '请选择' else eval(models.Config.objects.get(name=name, project=api.project).body)

    test_case = eval(api.body)
    print(test_case)
    summary = loader.debug_api(test_case, api.project.id, name=api.name, config=config,
                               user=request.user['username'])
    return Response(summary)


@api_view(['POST'])
@permission_classes([AllowAny])
def run_api_tree(request):
    """run api by tree
    {
        project: int
        relation: list
        name: str
        async: bool
        host: str
    }
    """
    # order by id default
    host = request.data["host"]
    project = request.data['project']
    relation = request.data["relation"]
    back_async = request.data["async"]
    name = request.data["name"]
    config = request.data["config"]

    config = None if config == '请选择' else eval(models.Config.objects.get(name=config, project__id=project).body)
    test_case = []

    for relation_id in relation:
        api = models.API.objects.filter(project__id=project, relation=relation_id, delete=0).order_by('id').values(
            'body')
        for content in api:
            api = eval(content['body'])
            test_case.append(api)

    # if back_async:
    #     tasks.async_debug_api.delay(test_case, project, name, config=parse_host(host, config))
    #     summary = loader.TEST_NOT_EXISTS
    #     summary["msg"] = "接口运行中，请稍后查看报告"
    # else:
    #     summary = loader.debug_api(test_case, project, name=f'批量运行{len(test_case)}条API',
    #                                config=parse_host(host, config), user=request.user)
    summary = loader.debug_api(test_case, project, name=f'批量运行{len(test_case)}条API',
                               config=config, user=request.user['username'])
    return Response(summary)
